package cn.lblbc.webbrowser

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lblbc.webbrowser.adapters.BackgroundImageAdapter
import cn.lblbc.webbrowser.adapters.AutoCompleteAdapter
import cn.lblbc.webbrowser.models.Bookmark
import cn.lblbc.webbrowser.models.HistoryItem
import cn.lblbc.webbrowser.utils.BackgroundImageManager
import cn.lblbc.webbrowser.utils.BookmarkManager
import cn.lblbc.webbrowser.utils.CompletedDownloadManager
import cn.lblbc.webbrowser.utils.CustomDownloader
import cn.lblbc.webbrowser.utils.DownloadUtils
import cn.lblbc.webbrowser.utils.HistoryManager
import cn.lblbc.webbrowser.utils.ImageCollectionSettings
import cn.lblbc.webbrowser.utils.ImageCollector
import cn.lblbc.webbrowser.utils.IncognitoManager
import cn.lblbc.webbrowser.utils.PermissionManager

class MainActivity : BaseActivity() {
    // 常量：用于Activity间传递书签URL的Intent Key
    private val EXTRA_BOOKMARK_URL = "cn.lblbc.webbrowser.EXTRA_BOOKMARK_URL"
    
    // 标志：用于区分地址栏文本是用户输入还是程序设置
    private var isProgrammaticTextChange = false

    // 视图与管理器初始化
    private lateinit var fragmentContainer: FrameLayout
    private val tabList = mutableListOf<Fragment>()
    private val tabTitleList = mutableListOf<String>()
    private var currentTabIndex = -1
    private lateinit var addressBar: EditText
    private lateinit var clearButton: ImageButton
    private lateinit var webProgressBar: ProgressBar
    private lateinit var backButton: ImageButton
    private lateinit var forwardButton: ImageButton
    private lateinit var homeScreenButton: ImageButton
    private lateinit var tabsButton: TextView
    private lateinit var menuButton: ImageButton
    private lateinit var backgroundImageView: ImageView
    private lateinit var navigationBar: View
    private lateinit var bookmarkManager: BookmarkManager
    private lateinit var historyManager: HistoryManager
    private lateinit var incognitoManager: IncognitoManager
    private lateinit var permissionManager: PermissionManager
    private lateinit var downloadUtils: DownloadUtils

    // 下载相关组件
    // 从Application获取全局下载管理器实例
    val customDownloader: CustomDownloader
        get() = (application as BrowserApplication).customDownloader
    val completedDownloadManager: CompletedDownloadManager
        get() = (application as BrowserApplication).completedDownloadManager
    private var pendingDownload: Bundle? = null
    private lateinit var suggestionsRecyclerView: androidx.recyclerview.widget.RecyclerView
    private var autoCompleteAdapter: AutoCompleteAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarColor()
        setContentView(R.layout.activity_main)

        // 初始化工具类
        bookmarkManager = BookmarkManager(this)
        historyManager = HistoryManager(this)
        incognitoManager = IncognitoManager(this)
        permissionManager = PermissionManager(this)
        downloadUtils = DownloadUtils(this)

        // 初始化视图、监听器
        initViews()
        setupListeners()

        // 处理从BookmarksActivity跳转过来的书签URL
        handleBookmarkUrlFromIntent()

        // 添加默认主页标签
        addHomeTab()
        updateTabsCounter()
    }

    /**
     * 处理从BookmarksActivity传递过来的书签URL（首次创建时调用）
     */
    private fun handleBookmarkUrlFromIntent() {
        val bookmarkUrl = intent.getStringExtra(EXTRA_BOOKMARK_URL)
        if (!bookmarkUrl.isNullOrEmpty()) {
            loadUrl(bookmarkUrl) // 加载书签对应的网页
            intent.removeExtra(EXTRA_BOOKMARK_URL) // 清除数据，避免重复处理
        }
    }

    /**
     * 当Activity已存在时，接收新的Intent（例如从BookmarksActivity返回时）
     */
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent) // 更新当前Activity的Intent
        handleBookmarkUrlFromIntent() // 重新处理书签URL
    }

    /**
     * 创建顶部菜单
     */
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    /**
     * 顶部菜单点击事件
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_bookmarks -> {
                showBookmarks()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    /**
     * 设置沉浸式状态栏
     */
    private fun setStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = 
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or 
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            window.statusBarColor = Color.TRANSPARENT
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.decorView.systemUiVisibility = 
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or 
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.statusBarColor = Color.TRANSPARENT
        }
    }

    /**
     * 初始化所有视图
     */
    private fun initViews() {
        fragmentContainer = findViewById(R.id.fragmentContainer)
        addressBar = findViewById(R.id.addressBar)
        clearButton = findViewById(R.id.clearButton)
        webProgressBar = findViewById(R.id.webProgressBar)
        backButton = findViewById(R.id.backButton)
        forwardButton = findViewById(R.id.forwardButton)
        homeScreenButton = findViewById(R.id.homeScreenButton)
        tabsButton = findViewById(R.id.tabsButton)
        menuButton = findViewById(R.id.menuButton)
        navigationBar = findViewById(R.id.navigationBar)
        backgroundImageView = findViewById(R.id.backgroundImageView)
        suggestionsRecyclerView = findViewById(R.id.suggestionsRecyclerView)
    }

    /**
     * 设置所有视图的点击/文本变化监听器
     */
    private fun setupListeners() {
        // 地址栏回车/前往按钮事件
        addressBar.setOnEditorActionListener { _, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_GO ||
                (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN)
            ) {
                loadUrl(addressBar.text.toString())
                hideKeyboard()
                hideAutoCompleteSuggestions()
                return@setOnEditorActionListener true
            }
            false
        }
        
        // 地址栏焦点变化监听器
        addressBar.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus && addressBar.text.isNotEmpty()) {
                showAutoCompleteSuggestions(addressBar.text.toString())
            } else {
                hideAutoCompleteSuggestions()
            }
        }

        // 地址栏文本变化监听器（控制清除按钮显示和自动联想推荐）
        addressBar.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                clearButton.visibility = if (s?.isNotEmpty() == true) View.VISIBLE else View.GONE
                
                // 自动联想推荐功能 - 只在非程序设置文本且地址栏有焦点时显示
                if (!s.isNullOrEmpty() && !isProgrammaticTextChange && addressBar.hasFocus()) {
                    showAutoCompleteSuggestions(s.toString())
                } else {
                    hideAutoCompleteSuggestions()
                }
            }
            override fun afterTextChanged(s: android.text.Editable?) {}
        })

        // 清除地址栏文本
        clearButton.setOnClickListener {
            addressBar.setText("")
            addressBar.requestFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(addressBar, InputMethodManager.SHOW_IMPLICIT)
            hideAutoCompleteSuggestions()
        }

        // 网页后退
        backButton.setOnClickListener {
            hideKeyboard()
            getCurrentWebViewFragment()?.goBack()
            updateNavigationState()
        }

        // 网页前进
        forwardButton.setOnClickListener {
            hideKeyboard()
            getCurrentWebViewFragment()?.goForward()
            updateNavigationState()
        }

        // 回到主页
        homeScreenButton.setOnClickListener {
            hideKeyboard()
            switchToHomeTabOrCreate()
        }

        // 显示标签网格
        tabsButton.setOnClickListener {
            hideKeyboard()
            showTabGrid()
        }

        // 显示底部菜单
        menuButton.setOnClickListener {
            hideKeyboard()
            showMenu()
        }
    }

    /**
     * 切换/创建主页标签
     */
    private fun switchToHomeTabOrCreate() {
        try {
            val homeTabIndex = tabList.indexOfFirst { it is HomeFragment }
            if (homeTabIndex != -1) {
                switchToTab(homeTabIndex)
            } else {
                addHomeTab()
            }
        } catch (e: Exception) {
            addHomeTab()
        }
    }

    /**
     * 显示底部弹出菜单
     */
    private fun showMenu() {
        val popupMenu = PopupMenu(this, menuButton)
        popupMenu.menuInflater.inflate(R.menu.bottom_menu, popupMenu.menu)

        // 更新无痕模式菜单项状态
        val incognitoItem = popupMenu.menu.findItem(R.id.menu_incognito)
        if (incognitoManager.isIncognitoMode()) {
            incognitoItem.setIcon(R.drawable.ic_incognito_active)
            incognitoItem.setTitle(R.string.exit_incognito_mode)
        } else {
            incognitoItem.setIcon(R.drawable.ic_incognito)
            incognitoItem.setTitle(R.string.incognito_mode)
        }

        // 更新书签按钮状态（添加/移除收藏）
        val currentFragment = getCurrentWebViewFragment()
        val toggleBookmarkItem = popupMenu.menu.findItem(R.id.menu_toggle_bookmark)
        if (currentFragment != null) {
            val url = currentFragment.getCurrentUrl()
            if (bookmarkManager.isBookmarked(url)) {
                toggleBookmarkItem.setIcon(R.drawable.ic_bookmark)
                toggleBookmarkItem.setTitle(R.string.remove_bookmark)
            } else {
                toggleBookmarkItem.setIcon(R.drawable.ic_bookmark_border)
                toggleBookmarkItem.setTitle(R.string.add_bookmark)
            }
        }

        // 菜单点击事件
        popupMenu.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.menu_toggle_bookmark -> {
                    toggleBookmark()
                    true
                }
                R.id.menu_bookmarks -> {
                    showBookmarks()
                    true
                }
                R.id.menu_history -> {
                    showHistory()
                    true
                }
                R.id.menu_downloads -> {
                    showDownloads()
                    true
                }
                R.id.menu_incognito -> {
                    toggleIncognitoMode()
                    true
                }
                R.id.menu_collected_images -> {
                    showImagesEntrance() // 调用修改后的 Activity 跳转方法
                    true
                }
                R.id.menu_settings -> {
                    startActivity(Intent(this, SettingsActivity::class.java))
                    true
                }
                else -> false
            }
        }
        popupMenu.show()
    }

    /**
     * 切换书签收藏状态（添加/移除）
     */
    private fun toggleBookmark() {
        val currentFragment = getCurrentWebViewFragment() ?: return
        val url = currentFragment.getCurrentUrl()
        val title = currentFragment.getTitle()

        if (bookmarkManager.isBookmarked(url)) {
            bookmarkManager.removeBookmark(url)
            Toast.makeText(this, R.string.bookmark_removed, Toast.LENGTH_SHORT).show()
        } else {
            val bookmark = Bookmark(title, url)
            bookmarkManager.addBookmark(bookmark)
            Toast.makeText(this, R.string.bookmark_added, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 切换无痕模式
     */
    private fun toggleIncognitoMode() {
        val isIncognito = incognitoManager.toggleIncognitoMode()
        Toast.makeText(
            this,
            if (isIncognito) R.string.incognito_mode_on else R.string.incognito_mode_off,
            Toast.LENGTH_SHORT
        ).show()
    }

    /**
     * 跳转书签Activity
     */
    private fun showBookmarks() {
        try {
            val intent = Intent(this, BookmarksActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法打开书签页面", Toast.LENGTH_SHORT).show()
        }
    }

    // Activity结果启动器，用于处理历史记录返回的URL
    private val historyResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == RESULT_OK) {
            val url = it.data?.getStringExtra("url")
            if (!url.isNullOrEmpty()) {
                loadUrl(url)
            }
        }
    }

    /**
     * 显示历史记录
     */
    private fun showHistory() {
        try {
            val intent = Intent(this, HistoryActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            historyResultLauncher.launch(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法打开书签页面", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 显示下载列表Fragment
     */
    private fun showDownloads() {
        try {
            val intent = Intent(this, DownloadsActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法打开书签页面", Toast.LENGTH_SHORT).show()
        }
    }


    private fun showImagesEntrance() {
        try {
            val intent = Intent(this, ImagesEntranceActivity::class.java)
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "无法显示图库", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 显示标签网格Fragment
     */
    private fun showTabGrid() {
        try {
            val tabGridFragment = TabGridFragment()
            val transaction = supportFragmentManager.beginTransaction()
            transaction.add(R.id.main, tabGridFragment)
            transaction.addToBackStack("tabGrid")
            transaction.commit()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 添加主页标签
     */
    fun addHomeTab() {
        try {
            val homeFragment = HomeFragment()
            tabList.add(homeFragment)
            tabTitleList.add("主页")
            switchToTab(tabList.size - 1)
            updateTabsCounter()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 添加新标签页（带默认URL）
     */
    fun addNewTab(url: String = "https://www.baidu.com") {
        try {
            val webViewFragment = WebViewFragment.newInstance(url)
            tabList.add(webViewFragment)
            tabTitleList.add(url)
            switchToTab(tabList.size - 1)
            updateTabsCounter()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 添加空白标签页
     */
    fun addBlankTab() {
        try {
            val webViewFragment = WebViewFragment.newInstance("about:blank")
            tabList.add(webViewFragment)
            tabTitleList.add("新标签页")
            switchToTab(tabList.size - 1)
            updateTabsCounter()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 加载URL
     */
    fun loadUrl(url: String) {
        try {
            val currentFragment = if (currentTabIndex >= 0 && currentTabIndex < tabList.size) {
                tabList[currentTabIndex]
            } else null

            if (currentFragment is HomeFragment) {
                val formattedUrl = formatUrl(url)
                replaceHomeWithWebView(formattedUrl)
                updateAddressBarWithUrl(formattedUrl)
            } else if (currentFragment is WebViewFragment) {
                val formattedUrl = formatUrl(url)
                currentFragment.loadUrl(formattedUrl)
                updateAddressBarWithUrl(formattedUrl)
            } else {
                addNewTab(formatUrl(url))
            }
        } catch (e: Exception) {
            addNewTab(formatUrl(url))
        }
    }

    /**
     * 将主页标签替换为WebView
     */
    private fun replaceHomeWithWebView(url: String) {
        try {
            if (currentTabIndex >= 0 && currentTabIndex < tabList.size) {
                // 创建新的WebView
                val webViewFragment = WebViewFragment.newInstance(url)

                // 从FragmentManager中移除当前的HomeFragment
                val transaction = supportFragmentManager.beginTransaction()
                transaction.remove(tabList[currentTabIndex])

                // 替换列表中的Fragment
                tabList[currentTabIndex] = webViewFragment
                tabTitleList[currentTabIndex] = url

                // 添加新的WebView到FragmentManager
                transaction.add(R.id.fragmentContainer, webViewFragment)
                transaction.commit()

                // 更新UI状态
                updateNavigationState()
                updateAddressBar()
                updateUiTransparency()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 格式化URL（补全协议头）
     */
    private fun formatUrl(url: String): String {
        return if (url.startsWith("http://") || url.startsWith("https://")) {
            url
        } else if (url.contains(".")) {
            // 如果URL包含点号但没有www前缀，则添加www前缀
            val formattedUrl = if (!url.startsWith("www.")) {
                "www.$url"
            } else {
                url
            }
            "https://$formattedUrl"
        } else {
            "https://www.baidu.com/s?wd=$url"
        }
    }

    /**
     * 获取当前的WebViewFragment
     */
    private fun getCurrentWebViewFragment(): WebViewFragment? {
        try {
            if (currentTabIndex >= 0 && currentTabIndex < tabList.size) {
                val currentFragment = tabList[currentTabIndex]
                return currentFragment as? WebViewFragment
            }
            return null
        } catch (e: Exception) {
            return null
        }
    }

    /**
     * 更新导航按钮状态（前进/后退是否可用）
     */
    private fun updateNavigationState() {
        try {
            val webViewFragment = getCurrentWebViewFragment()

            if (webViewFragment != null) {
                backButton.isEnabled = webViewFragment.canGoBack()
                backButton.alpha = if (webViewFragment.canGoBack()) 1.0f else 0.5f

                forwardButton.isEnabled = webViewFragment.canGoForward()
                forwardButton.alpha = if (webViewFragment.canGoForward()) 1.0f else 0.5f
            } else {
                backButton.isEnabled = false
                backButton.alpha = 0.5f
                forwardButton.isEnabled = false
                forwardButton.alpha = 0.5f
            }
        } catch (e: Exception) {
            backButton.isEnabled = false
            backButton.alpha = 0.5f
            forwardButton.isEnabled = false
            forwardButton.alpha = 0.5f
        }
    }

    /**
     * 更新地址栏内容
     */
    private fun updateAddressBar() {
        try {
            // 设置标志，表示这是程序设置的文本变化，不应显示推荐列表
            isProgrammaticTextChange = true
            
            if (currentTabIndex >= 0 && currentTabIndex < tabList.size) {
                val currentFragment = tabList[currentTabIndex]

                if (currentFragment is WebViewFragment) {
                    addressBar.setText(currentFragment.getCurrentUrl())
                } else {
                    addressBar.setText("")
                }
            } else {
                addressBar.setText("")
            }
            
            // 确保隐藏推荐列表
            hideAutoCompleteSuggestions()
            // 重置标志
            isProgrammaticTextChange = false
        } catch (e: Exception) {
            addressBar.setText("")
            // 确保在异常情况下也重置标志
            isProgrammaticTextChange = false
        }
    }

    /**
     * 用指定URL更新地址栏
     */
    fun updateAddressBarWithUrl(url: String) {
        try {
            // 设置标志，表示这是程序设置的文本变化，不应显示推荐列表
            isProgrammaticTextChange = true
            addressBar.setText(url)
            clearButton.visibility = if (url.isNotEmpty()) View.VISIBLE else View.GONE
            // 确保隐藏推荐列表
            hideAutoCompleteSuggestions()
            // 重置标志
            isProgrammaticTextChange = false
        } catch (e: Exception) {
            e.printStackTrace()
            // 确保在异常情况下也重置标志
            isProgrammaticTextChange = false
        }
    }

    /**
     * 更新网页加载进度
     */
    fun updateWebProgress(progress: Int) {
        try {
            if (progress < 100) {
                webProgressBar.visibility = View.VISIBLE
                webProgressBar.progress = progress
            } else {
                webProgressBar.visibility = View.GONE
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 显示进度条
     */
    fun showWebProgress() {
        try {
            webProgressBar.visibility = View.VISIBLE
            webProgressBar.progress = 0
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 隐藏进度条
     */
    fun hideWebProgress() {
        try {
            webProgressBar.visibility = View.GONE
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 显示自动联想推荐
     */
    private fun showAutoCompleteSuggestions(query: String) {
        try {
            // 获取历史记录
            val history = historyManager.getHistory()
            
            // 根据查询过滤历史记录
            val filteredHistory = history.filter { 
                it.title.contains(query, ignoreCase = true) || 
                it.url.contains(query, ignoreCase = true) 
            }.take(10) // 限制最多显示10个推荐项
            
            // 如果有匹配的历史记录，显示推荐列表
            if (filteredHistory.isNotEmpty()) {
                // 创建或更新适配器
                if (autoCompleteAdapter == null) {
                    autoCompleteAdapter = AutoCompleteAdapter(filteredHistory) { historyItem ->
                        // 点击推荐项时加载URL
                        loadUrl(historyItem.url)
                        hideKeyboard()
                        hideAutoCompleteSuggestions()
                    }
                    suggestionsRecyclerView.adapter = autoCompleteAdapter
                    suggestionsRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
                } else {
                    // 更新适配器数据
                    autoCompleteAdapter?.updateData(filteredHistory)
                }
                
                // 显示推荐列表
                suggestionsRecyclerView.visibility = View.VISIBLE
            } else {
                hideAutoCompleteSuggestions()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            hideAutoCompleteSuggestions()
        }
    }
    
    /**
     * 隐藏自动联想推荐
     */
    private fun hideAutoCompleteSuggestions() {
        suggestionsRecyclerView.visibility = View.GONE
    }
    
    /**
     * 更新标签页计数器
     */
    private fun updateTabsCounter() {
        try {
            tabsButton.text = tabList.size.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 更新标签页标题
     */
    fun updateTabTitle(fragment: WebViewFragment, title: String) {
        try {
            val index = tabList.indexOf(fragment)
            if (index != -1 && index < tabTitleList.size) {
                tabTitleList[index] = title
            }

            // 如果不是无痕模式，添加到历史记录
            if (!incognitoManager.isIncognitoMode()) {
                val url = fragment.getCurrentUrl()
                if (url.isNotEmpty() && url != "about:blank") {
                    val historyItem = HistoryItem(title, url)
                    historyManager.addHistoryItem(historyItem)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 切换到指定标签页
     */
    fun switchToTab(position: Int) {
        try {
            if (position in 0 until tabList.size) {
                if (currentTabIndex != position) {
                    currentTabIndex = position

                    // 使用FragmentManager显示当前标签页
                    val transaction = supportFragmentManager.beginTransaction()
                    val fragment = tabList[position]

                    // 先隐藏所有Fragment
                    for (i in 0 until tabList.size) {
                        val f = tabList[i]
                        if (supportFragmentManager.fragments.contains(f)) {
                            transaction.hide(f)
                        }
                    }

                    // 如果Fragment已经添加过，则显示它，否则添加它
                    if (supportFragmentManager.fragments.contains(fragment)) {
                        transaction.show(fragment)
                    } else {
                        transaction.add(R.id.fragmentContainer, fragment)
                    }

                    transaction.commit()

                    // 更新UI状态
                    updateNavigationState()
                    updateAddressBar()
                    updateUiTransparency()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 根据当前 Fragment 更新 UI 透明度（主页半透明，网页不透明）
     * 同时切换状态栏样式和恢复地址栏周围的内边距
     */
    private fun updateUiTransparency() {
        try {
            val fragment = if (currentTabIndex >= 0 && currentTabIndex < tabList.size) tabList[currentTabIndex] else null
            val addressBarLayoutView = findViewById<View>(R.id.addressBarLayout)
            val navBarView = findViewById<View>(R.id.navigationBar)

            // 获取状态栏高度（用于恢复顶部内边距）
            val resId = resources.getIdentifier("status_bar_height", "dimen", "android")
            val statusBarHeight = if (resId > 0) resources.getDimensionPixelSize(resId) else 0

            if (fragment is WebViewFragment) {
                // 浏览网页时：不透明白色，普通（非沉浸式）状态栏，深色图标
                addressBarLayoutView?.setBackgroundColor(Color.WHITE)
                navBarView?.setBackgroundColor(Color.WHITE)
                // 设置 addressBarLayout 顶部间距为 0
                val layoutParams = addressBarLayoutView?.layoutParams as androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
                layoutParams.topMargin = 0
                addressBarLayoutView.layoutParams = layoutParams

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    window.statusBarColor = Color.WHITE
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    window.statusBarColor = Color.WHITE
                }
            } else {
                // 主页：半透明，沉浸式状态栏
                addressBarLayoutView?.setBackgroundColor(Color.parseColor("#80FFFFFF"))
                navBarView?.setBackgroundColor(Color.parseColor("#80FFFFFF"))
                // 恢复 addressBarLayout 顶部间距为 48dp (转换为像素)
                val layoutParams = addressBarLayoutView?.layoutParams as androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
                layoutParams.topMargin = resources.getDimension(R.dimen.address_bar_top_margin).toInt()
                addressBarLayoutView.layoutParams = layoutParams

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    window.decorView.systemUiVisibility =
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    window.statusBarColor = Color.TRANSPARENT
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    window.decorView.systemUiVisibility =
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    window.statusBarColor = Color.TRANSPARENT
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭指定标签页
     */
    fun closeTab(position: Int) {
        try {
            if (position in 0 until tabList.size) {
                val fragment = tabList[position]

                // 从列表中移除
                tabList.removeAt(position)
                tabTitleList.removeAt(position)

                // 从FragmentManager中移除
                val transaction = supportFragmentManager.beginTransaction()
                transaction.remove(fragment)
                transaction.commit()

                // 更新当前标签页索引
                if (tabList.isEmpty()) {
                    currentTabIndex = -1
                    addHomeTab()
                } else {
                    // 如果关闭的是当前标签页，则切换到前一个标签页
                    if (currentTabIndex >= tabList.size) {
                        currentTabIndex = tabList.size - 1
                    }
                    switchToTab(currentTabIndex)
                }

                updateTabsCounter()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭所有标签页
     */
    fun closeAllTabs() {
        try {
            // 从FragmentManager中移除所有Fragment
            val transaction = supportFragmentManager.beginTransaction()
            for (fragment in tabList) {
                transaction.remove(fragment)
            }
            transaction.commit()

            // 清空列表
            tabList.clear()
            tabTitleList.clear()
            currentTabIndex = -1

            // 添加新的主页标签页
            addHomeTab()
            updateTabsCounter()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取标签页数量
     */
    fun getTabCount(): Int {
        return tabList.size
    }

    /**
     * 获取指定位置的标签页Fragment
     */
    fun getTabFragment(position: Int): Fragment? {
        return if (position in 0 until tabList.size) {
            tabList[position]
        } else {
            null
        }
    }

    /**
     * 处理返回键事件
     */
    override fun onBackPressed() {
        try {
            // 如果当前显示的是标签页网格视图，先关闭它
            if (supportFragmentManager.backStackEntryCount > 0) {
                supportFragmentManager.popBackStack()
                return
            }

            val currentFragment = getCurrentWebViewFragment()

            if (currentFragment != null && currentFragment.canGoBack()) {
                currentFragment.goBack()
            } else {
                super.onBackPressed()
            }
        } catch (e: Exception) {
            super.onBackPressed()
        }
    }

    /**
     * 隐藏软键盘
     */
    private fun hideKeyboard() {
        try {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(addressBar.windowToken, 0)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 设置待下载的文件信息
     */
    fun setPendingDownload(downloadInfo: Bundle) {
        pendingDownload = downloadInfo
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PermissionManager.PERMISSION_REQUEST_CODE) {
            // 检查Android版本
            val isAndroid13Plus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU

            // Android 13+ 不需要存储权限，直接下载
            if (isAndroid13Plus) {
                processPendingDownload()
                return
            }

            // 检查权限授予情况
            var allGranted = true
            for (i in permissions.indices) {
                val result = if (i < grantResults.size) grantResults[i] else PackageManager.PERMISSION_DENIED
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false
                }
            }

            if (allGranted) {
                processPendingDownload()
            } else {
                Toast.makeText(this, R.string.some_permissions_denied, Toast.LENGTH_SHORT).show()
                pendingDownload = null
            }
        }
    }

    /**
     * 处理待下载的文件
     */
    private fun processPendingDownload() {
        if (pendingDownload == null) return

        try {
            pendingDownload?.let { downloadInfo ->
                val url = downloadInfo.getString("url")
                val userAgent = downloadInfo.getString("userAgent")
                val contentDisposition = downloadInfo.getString("contentDisposition")
                val mimeType = downloadInfo.getString("mimeType")

                if (url.isNullOrEmpty()) {
                    Toast.makeText(this, "下载URL无效", Toast.LENGTH_SHORT).show()
                    pendingDownload = null
                    return@let
                }

                Toast.makeText(this, "准备下载...", Toast.LENGTH_SHORT).show()

                val isAndroid13Plus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU

                if (isAndroid13Plus) {
                    customDownloader.downloadFile(
                        url,
                        userAgent ?: "",
                        contentDisposition ?: "",
                        mimeType ?: "application/octet-stream"
                    )
                } else {
                    downloadUtils.downloadFile(
                        url,
                        userAgent ?: "",
                        contentDisposition ?: "",
                        mimeType ?: "application/octet-stream"
                    )
                }

                pendingDownload = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            pendingDownload = null
        }
    }
}
